//
//  MenuDataManager.m
//  NOAHWM
//
//  Created by Ryan on 13-6-14.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "MenuDataManager.h"
#import "JSON.h"
#import "NYMemberCenterDataManager.h"
#import "NSMutableArray+DeepCopy.h"

#define kMenuDownloaderKey  @"MenuDownloaderKey"
#define kMenuSynthesizeKey  @"MenuSynthesizeKey"

@implementation MenuDataManager

@synthesize uid;
@synthesize leftMenu,rightMenu;
@synthesize editMenu,elements;

#pragma mark - Singleton methods

- (id)init
{
    if(self = [super init])
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(asynMenuWithNotification:) name:kAsynMenuNotification object:nil];
        self.leftMenu = [NSMutableArray array];
        self.rightMenu = [NSMutableArray array];
        self.editMenu = [NSMutableArray array];
        self.elements = [NSMutableArray array];
        self.uid = @"";
    }
    return self;
}

+ (MenuDataManager *)sharedManager
{
    static MenuDataManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[MenuDataManager alloc] init];
    });
    return manager;
}

- (void)dealloc
{
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [elements release];
    [editMenu release];
    [leftMenu release];
    [rightMenu release];
    [super dealloc];
}

- (void)asynMenuWithNotification:(NSNotification *)notification
{
//   app/SaveAccountNewSeqForApp.jsp?callback=jsonp&accountId=001O0000006wEOTIA2&funcId=APPL20130605133739255169,APPL20130605133738255166&newSeq=2,1
    //当eidtMenu跟leftMenu一样时，菜单没有改变
    if(![self.editMenu isEqualToArray:self.leftMenu])
    {
        NSString *accountId = [NYMemberCenterDataManager sharedManager].loginMember.accountId;
        NSMutableString *funcId = [NSMutableString stringWithString:@""];
        NSMutableString *newSeq = [NSMutableString stringWithString:@""];
        for(NYMenu *firstMenu in self.editMenu)
        {
            NSInteger index = 0;
            for(NYMenu *secondMenu in firstMenu.children)
            {
                index++;
                [funcId appendString:[NSString stringWithFormat:@"%@,",secondMenu.funcId]];
                [newSeq appendString:[NSString stringWithFormat:@"%d,",index]];
            }
        }
        NSString *realFuncId = [funcId substringToIndex:funcId.length-1];
        NSString *realNewSeq = [newSeq substringToIndex:newSeq.length-1];
        [self synthesizeMenuListToServer:accountId funcId:realFuncId newSeq:realNewSeq];
    }
}

#pragma mark - Public methods
- (void)callServerToGetMenuList:(NSString *)accountId
{
    NSString *suburl = [NSString stringWithFormat:kMenuListUrl,@"jsonp",accountId];
    if([accountId isEqualToString:@""])
    {
        suburl = [suburl stringByAppendingString:@"app000024"];
    }
    else
    {
        suburl = [suburl stringByAppendingString:@"app000002"];
    }
    
    NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:kMenuDownloaderKey];
}

- (void)synthesizeMenuListToServer:(NSString *)accountId
                            funcId:(NSString *)funcId
                            newSeq:(NSString *)newSeq
{
    NSString *suburl = [NSString stringWithFormat:kSynthesizeMenuUrl,@"jsonp",accountId,funcId,newSeq];
    suburl = [suburl stringByAppendingString:@"app000054"];
    NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:kMenuSynthesizeKey];
}


#pragma mark - Parse Data

- (void)parseWithArray:(NSArray *)array forMenu:(NSMutableArray *)menu
{
    //解析左边菜单
    for(NSDictionary *dictMenu in array)
    {
        NYMenu *nym = [[NYMenu alloc] init];
        nym.funcId = [dictMenu objectForKey:@"funcId"];
        nym.funcName = [dictMenu objectForKey:@"funcName"];
        nym.isSticky = [[dictMenu objectForKey:@"isSticky"] boolValue];
        nym.children = [NSMutableArray array];
        NSArray *arrayTemp = [dictMenu objectForKey:@"children"];
        [self parseWithArray:arrayTemp forMenu:nym.children];
        [menu addObject:nym];
        [nym release];
    }
}

#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    if([downloader.purpose isEqualToString:kMenuDownloaderKey])
    {
        NSDictionary *dict = [str JSONValue];
        if([[dict objectForKey:@"result"] isEqualToString:@"1"])
        {
            self.uid = [dict objectForKey:@"uid"];
            [NYMemberCenterDataManager sharedManager].loginMember.roleId = [dict objectForKey:@"roleId"];
            
            NSDictionary *menuDict = [dict objectForKey:@"menu"];
            NSArray *leftArray = [menuDict objectForKey:@"left"];
            NSArray *rightArray = [menuDict objectForKey:@"right"];
            self.leftMenu = [NSMutableArray array];
            self.rightMenu = [NSMutableArray array];
            
            [self parseWithArray:leftArray forMenu:self.leftMenu];
            [self parseWithArray:rightArray forMenu:self.rightMenu];
            //deep copy an array
            self.editMenu = [self.leftMenu deepCopy];
            
            //保存权限控制元素
             NSArray *elementsArray = [dict objectForKey:@"elements"];
            self.elements = [NSMutableArray array];
            for(NSDictionary *elementDict in elementsArray)
            {
                NYElement *nye = [[NYElement alloc] init];
                nye.elementId = [[elementDict objectForKey:@"element"] objectForKey:@"elementId"];
                nye.showTypeCode = [elementDict objectForKey:@"showTypeCode"];
                [self.elements addObject:nye];
                [nye release];
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:kGetMenuSucceedNotification object:nil];
        }
        else
        {
            [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
            [[NSNotificationCenter defaultCenter] postNotificationName:kGetMenuErrorNotification object:nil];
        }
    }
    else
    {
//        NSDictionary *dict = [str JSONValue];
//        [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
    }
}
- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    if([downloader.purpose isEqualToString:kMenuDownloaderKey])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:kGetMenuErrorNotification object:nil];
    }
    [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
}

@end
